import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_learning/routes/app_pages.dart';
import 'package:flutter_learning/utils/ly_app_color.dart';
import 'package:flutter_learning/widgets/ly_custom_scrollview.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';

import 'bluetooth/ly_bluetooth_view.dart';
import 'ly_serialport_manager.dart';
import 'socket/ly_socket_manager.dart';
import 'widgets/ly_table_view.dart';

class PageInfo {
  final String pageName;
  final String routeName;
  const PageInfo({required this.pageName, required this.routeName});
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  late TabController controller;
  String? message;

  List<PageInfo> pages = const [
    PageInfo(pageName: "sliverTable", routeName: AppPages.table),
    PageInfo(pageName: "charts", routeName: AppPages.chartsView),
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = TabController(length: 2, vsync: this);
    // LYSocketManager.share.initSocket((int msgSize, List<int> data) {
    //   debugPrint('$data');
    // });
  }

  bool isV = true;
  @override
  Widget build(BuildContext context) {
    // var content = "鹅鹅鹅，曲项向天歌，白毛浮绿水，红掌拨清波。";
    // RegExp exp = RegExp(r"[`~!@#$^&*()=|{}':;.<>《》/?！￥…（）—【】‘；：”“。，、？ ]");
    // content = content.replaceAll(exp, " ");
    // debugPrint("=====$content====");
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(''),
      ),
      resizeToAvoidBottomInset: false,
      body: ListView.separated(
          itemBuilder: (ctx, index) {
            final page = pages[index];
            return GestureDetector(
              onTap: () {
                Get.toNamed(page.routeName);
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                height: 50,
                padding: const EdgeInsets.only(left: 15),
                alignment: Alignment.centerLeft,
                child: Text(
                  page.pageName,
                  style: const TextStyle(fontSize: 16, color: AppColor.blackColor),
                ),
              ),
            );
          },
          separatorBuilder: (ctx, index) {
            return const Divider(
              color: AppColor.blackColor,
              height: 1,
              indent: 15,
              endIndent: 15,
            );
          },
          itemCount: pages.length),
      // body: const Padding(padding: EdgeInsets.all(10), child: LYTableView()),
      // body: const LYBluetoothView(),
      // body: ListView(),

      // body: Column(
      //   children: [
      //     Expanded(
      //         child: TabBarView(
      //             controller: controller,
      //             children: [LYTextField(), LYTextField()])),
      //     SafeArea(
      //       child: Container(
      //         height: 50,
      //         color: Colors.red,
      //         child: TabBar(
      //           controller: controller,
      //           tabs: [
      //             Text('data'),
      //             Text("data1"),
      //           ],
      //         ),
      //       ),
      //     ),
      //   ],
      // ),
      // body: Column(
      //   mainAxisAlignment: MainAxisAlignment.center,
      //   children: [
      //     LYDatePicker(),
      //   ],
      // ),
      // body: MetaHumanContentView(isVertical: isV),
      // body: LYShimmer(),
      // body: LYGradientText(),
      // body: LYClickEffectsView(),
      // body: const LearningRiverPod(),
      // body: const LYDraggableView(),
      // body: Stack(
      //   fit: StackFit.expand,
      //   children: [
      //     Positioned.fill(
      //         child: Image.network(
      //             'https://v-moment-prod.jikeint.com/admin/0-frank.jpg')),
      //     Positioned.fill(child: HomePage()),
      //   ],
      // ),
      // body: Column(
      //   children: list,
      // ),
      // floatingActionButton: TextButton(
      //     onPressed: () async {
      //       // setState(() {
      //       //   isV = !isV;
      //       // });
      //       // List<Media>? result = await ImagesPicker.pick(
      //       //   count: 1,
      //       //   pickType: PickType.image,
      //       // );
      //       // if (result != null) {
      //       //   File file = File(result.first.path);
      //       //   final imageData = file.readAsBytesSync();
      //       //   saveImageToFile(imageData);
      //       // }
      //       // LYSocketManager.share.sendMessage(content: "hello");
      //       final res = await LYSerialPortManager.share.init();
      //
      //       if (res != null && res.isNotEmpty) {
      //         for (final device in res) {
      //           list.add(Text(
      //               'deviceName:${device.deviceName}productName:${device.productName}serialNumber:${device.serialNumber}'));
      //         }
      //         setState(() {});
      //       } else {
      //         EasyLoading.showToast('未获取到可用的外设',
      //             duration: const Duration(seconds: 5));
      //       }
      //     },
      //     child: const Text('获取可用外设')),
      // child: Text(isV ? '竖直' : '水平')),
    );
  }

  static Future<String> saveImageToFile(Uint8List imageData) async {
    String filePath = '';
    Directory applicationDir = await getApplicationDocumentsDirectory();
    bool isDirExist = await Directory("${applicationDir.path}/images").exists();
    if (!isDirExist) Directory("${applicationDir.path}/images").create();
    // 直接保存，返回的就是保存后的文件
    String fileName = "${DateTime.timestamp().toString()}.jpg";
    File saveFile = await File("${applicationDir.path}/images/$fileName").writeAsBytes(imageData);
    filePath = saveFile.path;
    debugPrint('======$filePath');
    return filePath;
  }
}
